package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.common.constants.WmNewsMessageContants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * articel文章上下架监听器
 */
@Component
@Slf4j
public class ArticleUpDownListener {


    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @KafkaListener(topics = WmNewsMessageContants.WMNEWS_DOWN_OR_UP)
    public void onMessage(String message){
        //1.校验参数
        if(message == null){
            return;
        }
        //2.把字符串转换成一个MAP集合
        Map<String,Object> map = JSON.parseObject(message, Map.class);
        //3.根据传输的ID和上下架修改文章配置表的数据即可
        //3.1 查询此文章的配置信息
        LambdaQueryWrapper<ApArticleConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleConfig::getArticleId,map.get("articleId"));
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(wrapper);
        if(apArticleConfig == null){
            throw new RuntimeException("文章不存在....");
        }
        //3.2 修改文章状态 (状态别弄错了。)
        if((Integer) map.get("enable") == 0){//代表下架
            apArticleConfig.setIsDown(true);
        }else{ //代表上架
            apArticleConfig.setIsDown(false);
        }
        apArticleConfigMapper.updateById(apArticleConfig);
    }
}
